package com.boot.main.config.dealnull;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class MyBeanSerializerModifier extends BeanSerializerModifier {
    private JsonSerializer _nullArrayJsonSerializer = new MyNullArrayJsonSerializer();
    private JsonSerializer _nullJsonSerializer = new MyNullJsonSerializer();
    private JsonSerializer _nullObjectSerializer = new MyNullObjectJsonSerializer();
    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List beanProperties){
        for (int i=0;i<beanProperties.size();i++){
            BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
            if(isArrayType(writer)){
                writer.assignNullSerializer(this._nullArrayJsonSerializer);
            }else if(isStringOrNumberType(writer)){
                writer.assignNullSerializer(this._nullJsonSerializer);
            }else{
                writer.assignNullSerializer(this._nullObjectSerializer);
            }
        }
        return beanProperties;
    }

    protected boolean isArrayType(BeanPropertyWriter writer){
        Class clazz = writer.getPropertyType();
        return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
    }
    protected boolean isStringOrNumberType(BeanPropertyWriter writer){
        Class clazz = writer.getPropertyType();
        return clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(int.class) || clazz.equals(Double.class) || clazz.equals(Short.class)
                || clazz.equals(Long.class) || clazz.equals(short.class) || clazz.equals(double.class) || clazz.equals(long.class) || clazz.equals(Date.class)
                || clazz.equals(BigDecimal.class);
    }
}

